<template>
  <div class="container">
    <div class="app-container">
      <!-- 展示树形结构 -->
      <el-tree :expand-on-click-node="false" default-expand-all :data="depts" :props="defaultProps">
        <!-- 节点结构 -->
        <!-- v-slot="{ node, data }" 只能作用在template -->
        <template v-slot="{ data }">
          <el-row style="width:100%;height:40px ;align-items: center ;line-height: 40px;" type="flex" justify="space-between" align="middle">
            <el-col :span="20">{{ data.name }}</el-col>
            <el-col :span="6">
              <span class="tree-manager" style="margin-right: 60px;">{{ data.managerName }}</span>
              <!-- $event 实参 表示类型 -->
              <el-dropdown @command="operateDept($event, data.id)">
                <!-- 显示区域内容 -->
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <!-- 下拉菜单选项 -->
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
      <el-dialog
        :title="translate"
        :visible.sync="showDialog"
        width="500px"
        @close="clear"
      >
        <el-form ref="formObj" label-width="100px" :model="formObj" :rules="rules">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="formObj.name" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="formObj.code" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="managerId">
            <!-- <el-input v-model="formObj.managerId" /> -->
            <el-select v-model="formObj.managerId" placeholder="请选择">
              <el-option
                v-for="item in managerList"
                :key="item.id"
                :label="item.username"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="formObj.introduce" type="textarea" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="clear">取 消</el-button>
          <el-button @click="submit">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <!-- 放置弹层 -->
    <!-- 表示会接受子组件的事件  update:showDialog, 值 => 属性 -->
    <add-dept :current-node-id="currentNodeId" :show-dialog.sync="showDialog" @updateDepartment="getDepartment" />
  </div>
</template>
<script>
import { addDepartment, delDepartment, getDepartment, getDepartmentDetail, getDepartmentManager, updateDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Department',
  data() {
    return {
      parentId: null,
      showDialog: false,
      list: [],
      depts: [],
      managerList: [],
      formObj: {
        code: '',
        introduce: '',
        managerId: '',
        name: ''
      },
      rules: {
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let temp = this.list
              if (this.formObj.id) {
                temp = temp.filter(item => item.id !== this.formObj.id)
              }
              if (temp.some(item => item.code === value)) {
                callback(new Error('部门编码已存在'))
              } else {
                callback()
              }
            }
          }

        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 0, max: 100, message: '长度在 0到 100 个字符', trigger: 'blur' }
        ],
        managerId: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let temp = this.list
              if (this.formObj.id) {
                temp = temp.filter(item => item.id !== this.formObj.id)
              }
              if (temp.some(item => item.name === value)) {
                callback(new Error('部门名称已存在'))
              } else {
                callback()
              }
            }
          }

        ]
      }
    }
  },
  computed: {
    translate() {
      return this.formObj.id ? '编辑部门' : '新增部门'
    }
  },
  created() {
    this.getDepartment()
    this.getDepartmentManager()
  },
  methods: {
    async getDepartmentManager() {
      const res = await getDepartmentManager()
      this.managerList = res
    },
    submit() {
      if (this.formObj.id) {
        this.updateDepartment()
      } else {
        this.$refs.formObj.validate(async isOk => {
          if (isOk) {
            await this.addDepartment()
            this.clear()
          }
        })
      }
    },
    async updateDepartment() {
      await updateDepartment(this.formObj)
      this.$message.success('编辑部门成功')
      this.clear()
    },
    async addDepartment() {
      await addDepartment({
        ...this.formObj,
        pid: this.parentId
      })
      this.$message.success('添加部门成功')
    },
    clear() {
      this.showDialog = false
      this.getDepartment()
      this.$refs.formObj.resetFields()
      this.formObj = {
        code: '',
        introduce: '',
        managerId: '',
        name: '' }
      this.parentId = null
    },
    // 封装好方法
    async getDepartment() {
      const result = await getDepartment()
      this.list = result
      this.depts = transListToTreeData(result, 0)
    },

    async delDepartment(id) {
      await delDepartment(id)
      this.$message.success('删除部门成功')
      this.clear()
    },
    async getDepartmentDetail(id) {
      const res = await getDepartmentDetail(id)
      this.formObj = res
    },
    operateDept(type, id) {
      if (type === 'add') {
        this.showDialog = true
        this.parentId = id
      }
      if (type === 'edit') {
        this.showDialog = true
        this.parentId = id
        this.getDepartmentDetail(this.parentId)
      }
      if (type === 'del') {
        this.parentId = id
        this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async() => {
            this.delDepartment(this.parentId)
          })
      }
    }
  }
}
</script>
<style scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px;
}
</style>
